import { delay } from "redux-saga";
import { call, take, put, race, select, takeEvery } from "redux-saga/effects";
import { MAP_READY, MAP_LOADING, MAP_COLS, MAP_ROWS } from "../constants/MapConst";

export function* loadingMap() {
    let loopCnt = 0;
    let loading = 0;
    while (true) {
        const state = yield select();
        if (loading === 0) {
            yield put({
                type: MAP_LOADING, payload: {
                    data: state.get("map").get("data"),
                    from: 0
                }
            });
            if (!(loopCnt < MAP_ROWS)) {
                loopCnt = 0;
                loading = 1;
            }
        } else if (loading === 1) {
            yield put({
                type: MAP_LOADING, payload: {
                    data: state.get("map").get("data"),
                    from: 1
                }
            });
            if (!(loopCnt < MAP_ROWS)) {
                loopCnt = 1;
                loading = 2;
            }
        } else {
            loopCnt = 0;
            loading = 0;
            break;
        }
        loopCnt++;
        yield call(delay, 30);
    }
}

export default function* watchMapLoading() {
    yield takeEvery(MAP_READY, loadingMap);
}
